<!--
 * @Description: 通知维护
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 14:23:07
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div style="display:flex;align-items: flex-end;justify-content: space-between;">
          <div class="tabtop">
            <div v-for="(item, index) in arr1" :key="index" @click="change1('hidactive1','active1',item.value)">
              <div :class="active1 == index+1 ? 'active' : 'text'">{{ item.text }}</div>
            </div>
          </div>
          <el-button size="medium" style="height: 36px;margin-right:20px" class="bottom_all" @click="submit()">保 存</el-button>
        </div>
        <div class="d">
          <!-- <div v-loading="loading" class="a scroll" style="max-height:648px"> -->
          <div v-loading="loading" class="a scroll">
            <div v-if="active1==2">
              <el-tree ref="tree" :data="arr2" default-expand-all :expand-on-click-node="false">
                <span slot-scope="{ node,data }" class="custom-tree-node tree-line">
                  <span v-if="data.children">
                    <i :class="data.icon"></i>
                    <span>{{ node.label }}</span>
                  </span>
                  <el-radio-group v-else v-model="active2" @change="change('hidactive2','active2',active2)">
                    <el-radio :label="data.value">
                      <span>{{ node.label }}</span>
                    </el-radio>
                  </el-radio-group>
                </span>
              </el-tree>
            </div>
            <div v-else>
              <el-radio-group v-model="active2" @change="change('hidactive2','active2',active2)">
                <template v-for="(item, index) in arr2">
                  <div :key="index" class="radio-bg">
                    <el-radio :label="item.value">{{ item.label }}</el-radio>
                  </div>
                </template>
              </el-radio-group>
            </div>
          </div>
          <div class="b">
            <div class="b-a">通知业务</div>
            <!-- <div v-loading="loading1" class="b-b scroll" style="max-height:600px"> -->
            <div v-loading="loading1" class="b-b scroll">
              <el-radio-group v-model="active3" @change="change('hidactive2','active3',active3)">
                <template v-for="(item, index) in arr3">
                  <div :key="index" class="radio-bg">
                    <el-radio :label="item.id">{{ item.itemName }}</el-radio>
                  </div>
                </template>
              </el-radio-group>
            </div>
          </div>
          <div class="c">
            <div class="b-a">通知对象</div>
            <div class="c-a">
              <div>
                <el-form>
                  <el-form-item>
                    <span slot="label">选择类别</span>
                    <el-select v-model="type" placeholder="请选择">
                      <el-option label="组织" value="1"></el-option>
                      <el-option label="角色" value="2"></el-option>
                      <el-option label="人员" value="3"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
              <div class="e">
                <div class="e-a">
                  <div class="b-a">选择</div>
                  <!-- <div v-loading="loading2" class="e-c scroll" style="max-height:475px"> -->
                  <div v-loading="loading2" class="e-c scroll">
                    <el-tree v-if="type==1" ref="tree" :key="time" :data="arr4" show-checkbox :props="defaultProps1" :expand-on-click-node="false" :check-on-click-node="true">
                      <span slot-scope="{ node }" class="custom-tree-node tree-line">
                        <span>{{ node.label }}</span>
                      </span>
                    </el-tree>
                    <el-checkbox-group v-if="type==2" v-model="active4">
                      <div v-for="(item, index) in arr4" :key="index" class="radio-bg">
                        <el-checkbox :label="item">
                          <span>
                            <i class="icon iconfont icontree_icon_team"></i>
                            {{ item.name }}
                          </span>
                        </el-checkbox>
                      </div>
                    </el-checkbox-group>
                    <!-- default-expand-all -->
                    <el-tree v-if="type==3" ref="tree3" :data="mailList" show-checkbox :props="props2" :expand-on-click-node="false" :check-on-click-node="true" lazy :load="loadNode" default-expand-all>
                      <span slot-scope="{ node }" class="custom-tree-node tree-line">
                        <span>{{ node.label }}</span>
                      </span>
                    </el-tree>
                  </div>
                </div>
                <div class="e-b">
                  <div class="e-b-a">
                    <el-button size="mini" class="botton" @click="add()">&#61; &#160; &#160;&#62;</el-button>
                    <div>
                      <el-button size="mini" class="botton" @click="del()">&#60; &#160; &#160;&#61;</el-button>
                    </div>
                    <el-button size="mini" class="botton" @click="clear()">清空已选</el-button>
                  </div>
                </div>
                <div class="e-a">
                  <div class="b-a">已选择</div>
                  <!-- <div class="e-c scroll" style="max-height:475px"> -->
                  <div class="e-c scroll">
                    <el-checkbox-group v-model="active5">
                      <div v-for="(item, index) in arr5" :key="index" class="radio-bg">
                        <el-checkbox :label="item.id">
                          <span>
                            <i class="icon iconfont icontree_icon_team"></i>
                            {{ item.name }}
                          </span>
                        </el-checkbox>
                      </div>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { getDicType } from "@/api/common.js";
import { queryPage as queryorganPage } from "@/api/basedata/organization.js";
import { formatTreeData } from "@/utils/utils";
import { queryPage as queryrolePage } from "@/api/basedata/role.js";
import { saveOrUpdate, targetList, query_mail_list } from "@/api/basicConfig/notice.js";
import breaDcrumb from "@/components/breadcrumb";
import { getUserAutList } from "@/api/common.js";
import { getUserInfo } from "@/utils/auth.js";
export default {
  components: {
    breaDcrumb,
  },
  data() {
    return {
      mailList: [],
      UserInfo: '',
      arr1: [
        {
          text: "公司",
          value: 1,
          name: "organization",
        },
        {
          text: "站点",
          value: 2,
          name: "points",
        },
      ],
      active1: 0,
      hidactive1: 4,
      /*公司*/
      arr2: [],
      active2: null,
      hidactive2: null,
      loading: false,
      /*通知道业务点*/
      arr3: [],
      active3: null,
      hidactive3: null,
      loading1: false,
      /*用户*/
      loading2: false,
      type: "1",
      defaultProps1: {
        children: "children",
        label: "name",
      },
      time: "",
      oldarr4: [],
      arr4: [],
      active4: [],
      oldarr5: [],
      arr5: [],
      active5: [],
      props2: {
        label: 'name'
      }
    };
  },
  watch: {
    active1: {
      handler() {
        switch (this.active1) {
          case 1: {
            console.log(this.arr2?.[0]);
            this.active2 = this.arr2?.[0].value;
            this.getcode("newsInform");
            return;
          }
          case 2: {
            this.active2 = this.arr2?.[0]?.children[0]?.value;
            this.getcode("newsInfomZandian");
            return;
          }
          default: {
            break;
          }
        }
      },
      deep: false,
      immediate: true,
    },
    type: {
      handler() {
        this.loading2 = true;
        switch (this.type) {
          case "1": {
            queryorganPage({
              page: 1,
              pageSize: 999999,
              showEnable: 0,
            }).then((res) => {
              if (res.code === 1001) {
                this.oldarr4 = res.data.data;
                this.fiterarr();
              }
            });
            this.clear()
            this.getarr5();
            return;
          }
          case "2": {
            queryrolePage({
              page: 1,
              pageSize: 999999,
              roleEentrance: "entrance_manager",
              enable: 1,
            }).then((res) => {
              this.oldarr4 = res.data.data;
              this.fiterarr();
            });
            this.clear()
            this.getarr5();
            return;
          }
          case "3": {
            return;
          }
          default: {
            break;
          }
        }
      },
      deep: false,
      immediate: true,
    },
    arr5: {
      handler() {
        this.fiterarr();
      },
      deep: false,
      immediate: true,
    },
  },
  async created() {
    this.UserInfo = await getUserInfo();
    this.arr2 = await getUserAutList()
    this.active1 = 1
  },
  methods: {
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.clear()
        query_mail_list({ page: 1, pageSize: 999999, id: this.UserInfo.companyId }).then((res) => {
          let type = res.data.type
          let arrList = res.data.body.data.map((res) => {
            if (type == 'type_user') {
              return {
                type: type,
                name: res.name,
                id: res.id,
                isLeaf: true,
                userType: true
              }
            } else {
              return {
                type: type,
                name: res.name,
                id: res.id,
                userType: false
              }
            }
          })
          resolve(arrList);
          this.fiterarr();
          this.getarr5();
        })
      } else {
        if (node.data.type == 'type_user') {
          resolve([]);
        } else {
          query_mail_list({ page: 1, pageSize: 999, id: node.data.id }).then((res) => {
            let type = res.data.type
            let arrList = res.data.body.data.map((res) => {
              if (type == 'type_user') {
                return {
                  type: type,
                  name: res.name,
                  id: res.id,
                  isLeaf: true,
                  userType: true
                }
              } else {
                return {
                  type: type,
                  name: res.name,
                  id: res.id,
                  userType: false
                }
              }
            })
            resolve(arrList);
          })
        }
      }
    },
    /*修改时确认是否保存*/
    change(hid, show, value) {
      let _this = this;
      console.log(_this.hidactive2);
      console.log(_this.active3);
      if (hid == "hidactive3" && !_this.hidactive2) {
        _this[show] = value;
        _this[hid] = value;
        _this.getarr5();
        return;

      }
      let allHasData = _this.oldarr5.filter((item) =>
        _this.arr5.some((items) => item.id == items.id)
      );
      let deleteData = _this.oldarr5.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      let addData = _this.arr5.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      if ((deleteData.length !== 0 || addData.length !== 0) && _this[hid]) {
        this.$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            _this.submit();
            _this[show] = _this[hid];
          })
          .catch(() => {
            _this[show] = value;
            _this[hid] = value;
            _this.getarr5();
          });
      } else {
        _this[show] = value;
        _this[hid] = value;
        _this.getarr5();
      }
    },
    /**切换公司各站点时的保存提示优化，不能和其他区域饿修改监听进行统一的使用*/
    change1(hid, show, value) {
      let _this = this;
      _this.time = new Date().getTime()
      let allHasData = _this.oldarr5.filter((item) =>
        _this.arr5.some((items) => item.id == items.id)
      );
      let deleteData = _this.oldarr5.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      let addData = _this.arr5.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      if ((deleteData.length !== 0 || addData.length !== 0) && _this[hid]) {
        this.$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            _this.submit();
            console.log(_this[hid]);
            _this[show] = _this[hid];
            _this.active3 = null
            _this.hidactive2 = null
          })
          .catch(() => {
            _this[show] = value;
            _this[hid] = value;
            _this.getarr5();
            _this.active3 = null
            _this.hidactive2 = null
          });
      } else {
        _this[show] = value;
        _this[hid] = value;
        _this.active3 = null
        _this.hidactive2 = null
        _this.getarr5();
      }
    },
    /**获取对应的业务点*/
    getcode(code) {
      getDicType({ code: code }).then((res) => {
        this.arr3 = res.data.items;
        this.loading1 = false;
      });
    },
    /**组织*/
    async fiterarr() {
      let key = this.oldarr4.filter((item) =>
        this.arr5.some((items) => items.id == item.id)
      );
      this.arr4 = this.oldarr4.filter(
        (item) => !key.some((items) => items.id == item.id)
      );
      if (this.type == 1) {
        this.arr4 = formatTreeData(
          this.arr4,
          "id",
          "parentId",
          "children",
          "parent_id"
        );
      }
      this.loading2 = false;
    },
    /**清空*/
    clear() {
      this.arr5 = [];
    },
    /**添加*/
    add() {
      let key = [];
      if (this.type == 2) {
        key = this.active4;
        key.forEach((res) => {
          res.foreignType = 3;
        });
      } else if (this.type == 3) {
        key = this.$refs.tree3.getCheckedNodes();
        key.forEach((res) => {
          res.foreignType = 1;
        });
      } else if (this.type == 1) {
        key = this.$refs.tree.getCheckedNodes();
        key.forEach((res) => {
          res.foreignType = 2;
        });
      }
      key = key.filter((res) => {
        if (res.userType) {
          let obj = {
            id: res.id,
            name: res.name,
            foreignType: res.foreignType,
            userType: res.userType
          };
          return obj;
        }
      });
      console.log(JSON.parse(JSON.stringify(key)))
      let hash = {};
      let setKey = (item, cur) => {
        hash[cur.id] ? '' : hash[cur.id] = true && item.push(cur);
        return item
      }
      this.arr5 = [...key, ... this.arr5].reduce(setKey, [])

    },
    /**删除*/
    del() {
      let key = this.arr5.filter((item) =>
        this.active5.some((items) => items == item.id)
      );
      this.arr5 = this.arr5.filter(
        (item) => !key.some((items) => items.id == item.id)
      );
    },
    /**获取绑定关系*/
    getarr5() {
      if (this.active3) {
        let data = new Object();
        data.foreignType = this.$fromatTable(
          this.arr1,
          this.active1,
          "value",
          "name"
        );
        data.foreignId = this.active2;
        data.businessId = this.active3;
        targetList(data).then((res) => {
          console.log(res);
          this.arr5 = res.data.map(res => {
            let obj = {
              foreignType: res.foreignType,
              id: res.foreignId,
              name: res.foreignName,
              dataId: res.id,
              noticeManagerId: res.noticeManagerId
            }
            return obj
          })
          this.oldarr5 = JSON.parse(JSON.stringify(this.arr5))
        });
      } else {
        this.arr5 = [];
        this.oldarr5 = []
      }
    },
    /**保存绑定关系*/
    submit() {
      let _this = this
      if (!_this.active3) {
        _this.$message({
          message: "请选择通知的业务点",
          type: "warning",
        });
        return;
      }
      let allHasData = _this.oldarr5.filter((item) =>
        _this.arr5.some((items) => item.id == items.id)
      );
      let deleteData = _this.oldarr5.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      let addData = _this.arr5.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      addData = addData.map((res) => {
        let obj = {
          status: 1,
          foreignId: res.id,
          foreignName: res.name,
          foreignType: res.foreignType,
        };
        return obj;
      });
      deleteData = deleteData.map((res) => {
        let obj = {
          status: 0,
          id: res.dataId,
          foreignId: res.id,
          foreignName: res.name,
          foreignType: res.foreignType,
          noticeManagerId: res.noticeManagerId
        };
        return obj;
      });
      let arr = [...deleteData, ...addData];
      if (arr.length == 0) {
        _this.$message({
          message: "请选择通知的对象或通知对象无修改",
          type: "warning",
        });
        return;
      }
      let data = new Object();
      data.foreignType = this.$fromatTable(
        this.arr1,
        this.active1,
        "value",
        "name"
      );
      data.foreignId = this.active2;
      data.businessId = this.active3;
      data.status = 1;
      data.targetList = arr;
      console.log(JSON.parse(JSON.stringify(data)))
      saveOrUpdate(data).then((res) => {
        if (res.code == 1001) {
          _this.$message({
            message: "保存成功",
            type: "success",
          });
        }
        this.getarr5();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.d {
  height: calc(100% - 62px);
  width: 100%;
  display: flex;
  padding: 20px;
}
.a,
.b,
.c {
  min-height: 600px;
  height: 100%;
  border: 1px solid rgba(225, 229, 237, 1);
  border-radius: 4px;
}
.a {
  flex: 1;
  padding: 20px;
  margin-right: 10px;
  overflow: auto;
}
.b {
  flex: 1.5;
  margin: 0 10px;
  max-width: 300px;
}
.c {
  flex: 4;
  margin-left: 10px;
}
.c-a {
  padding: 20px;
  height: calc(100% - 48px);
}
.b-a {
  height: 48px;
  font-size: 12px;
  font-weight: bold;
  background: #e1e5ed;
  color: #000000;
  @include discen;
}
.b-b {
  height: calc(100% - 48px);
  padding: 20px;
  overflow: auto;
}
.e {
  display: flex;
  height: calc(100% - 54px);
}
.e-b {
  // flex: 1;
  display: flex;
  align-items: center;
  width: 130px;
}
.e-b-a {
  width: 100%;
  text-align: center;
}
.e-a {
  border: 1px solid rgba(225, 229, 237, 1);
  border-radius: 4px;
  flex: 2;
  height: 100%;
  overflow: auto;
}
.e-c {
  height: calc(100% - 48px);
  padding: 20px;
}
.botton {
  margin: 20px 0 0 0;
  width: 88px;
}
.tabtop {
  width: 381px;
}
.radio-bg {
  height: 28px;
}
</style>
